package com.starblink.mine.personhome.ui.wishlist.ui.wishlistboards.ui

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.utils.bindingAdapter
import com.starblink.android.basic.brv.utils.divider
import com.starblink.android.basic.brv.utils.linear
import com.starblink.android.basic.brv.utils.models
import com.starblink.android.basic.brv.utils.setup
import com.starblink.android.basic.const.NavParamsKeyConst
import com.starblink.android.basic.ext.ApolloValSetExt.apolloValue
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.setEmptyViewForWishTemplate
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectWishListEvent
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.mine.R
import com.starblink.mine.databinding.FragmentWishlistBoardsBinding
import com.starblink.mine.databinding.ItemWishlistBoardBinding
import com.starblink.rocketreserver.FetchWishListsByAccountIdV2Query
import kotlinx.coroutines.launch

/**
 * 个人首页-客态-Wishlist子页-Boards子页
 */
class WishlistBoardsFragment : BaseTVMFragment<FragmentWishlistBoardsBinding, WishlistBoardsVM>() {
    companion object {
        private const val TAG = "WishlistBoardsFragment"
        fun newInstance(accountId: String, accountDeleted: Boolean = false) =
            WishlistBoardsFragment().apply {
                arguments = bundleOf(
                    MineManager.KEY_USER_ID to accountId,
                )
            }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentWishlistBoardsBinding {
        return FragmentWishlistBoardsBinding.inflate(inflater, container, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SKLogger.e("dss", "WishlistBoardsFragment-onCreate")
    }

    override fun initData() {
        arguments?.run {
            getString(MineManager.KEY_USER_ID)?.let {
                viewModel.accountId = it
            }
        }
    }

    override fun initView(view: View) {
        super.initView(view)
        //初始化列表相关
        viewBinding.rv.linear().divider {
            setColor(Color.TRANSPARENT)
            setDivider(12, true)
            startVisible = true
            endVisible = true
        }.setup {
            addType<FetchWishListsByAccountIdV2Query.WishList, ItemWishlistBoardBinding>(
                it
            )

            onBind {
                val viewBinding = getBinding<ItemWishlistBoardBinding>()
                val wishlist = getModel<FetchWishListsByAccountIdV2Query.WishList>().wishListF

                viewBinding.root.setData(
                    wishListItem = wishlist,
                    position = layoutPosition,
                    showSaveBtn = true,
                    itemClickCallback = {
                        navigationTo(RoutePage.Wishlist.WISHLIST_DETAILS) {
                            withBoolean(NavParamsKeyConst.WISHLIST_IS_MASTER, false)
                            withString(
                                NavParamsKeyConst.WISHLIST_USER_ID,
                                wishlist.accountInfo.accountF.id
                            )
                            withString(
                                NavParamsKeyConst.WISHLIST_USER_IMG,
                                wishlist.accountInfo.accountF.headImage
                            )
                            withString(
                                NavParamsKeyConst.WISHLIST_USER_NAME,
                                wishlist.accountInfo.accountF.userName
                                    ?: wishlist.accountInfo.accountF.username
                            )
                            withObject(NavParamsKeyConst.WISHLIST_BOARD_ITEM, wishlist)
                        }
                    },
                    spmPageValue = SpmPageDef.Page_10213
                )
            }
        }

        viewBinding.page.onEmpty {
            post {
                setEmptyViewForWishTemplate(
                    title = "No Boards yet",
                    subTitle = "This account has not added \nanything to Boards",
                    marginTop = 32.dp,
                )
            }
        }
        viewBinding.page.onError {
            val view = findViewById<ImageView>(R.id.icon)
            (view.layoutParams as ViewGroup.MarginLayoutParams)
                .setMargins(0, 53.dp, 0, 0)
        }

        viewBinding.page.onLoading {
            val ll = findViewById<LinearLayout>(R.id.ll_loading)
            (ll.layoutParams as ViewGroup.MarginLayoutParams)
                .setMargins(0, 141.dp, 0, 0)
        }

        viewBinding.page.onRefresh {
            viewModel.getWishLists(refresh = true)
        }
        viewBinding.page.onLoadMore {
            viewModel.getWishLists(refresh = false)
        }
    }

    override fun startObserve() {
        iniEventListener()

        viewModel.listResponseLiveData.observe(this) {
            if (viewBinding.rv.models.isNullOrEmpty() || it.refresh) {
                // 刷新或页面销毁恢复
                viewBinding.page.addData(ArrayList(it.totalList)) {
                    it.totalList.isNotEmpty()
                }
            } else {
                // 加载更多
                viewBinding.page.addData(it.pageList) {
                    it.pageList.isNotEmpty()
                }
            }
        }

        viewModel.mLoadActionLiveData.observe(this) {
            when (it.action) {
                LoadAction.STATE_ERROR -> {
                    viewBinding.page.showError()
                }

                LoadAction.STATE_NO_DATA -> {
                    viewBinding.page.finishLoadMoreWithNoMoreData()
                }
            }
        }

        // 客态-加载数据
        viewBinding.page.showLoading(refresh = true)
    }

    private fun iniEventListener() {
        // 监听心愿单收藏事件
        FlowBus.with<CollectWishListEvent>(FlowConst.COLLECT_WISHLIST_EVENT).register(this) {
            SKLogger.e("dss", "WishlistBoardsFragment-CollectWishListEvent")
            // 个人首页-客态-Wishlist子页-Boards子页，当该用户的心愿单收藏状态发生修改时，更新状态
            if (it.wishlistAccountId.isNotEmpty() && it.wishlistAccountId == viewModel.accountId && viewModel.listResponseLiveData.value != null) {
                lifecycleScope.launch {
                    for ((index, wishList) in viewModel.listResponseLiveData.value!!.totalList.withIndex()) {
                        if (it.wishlistId == wishList.wishListF.id && it.latestCollectStatus != wishList.wishListF.collectStatus) {
                            SKLogger.e("dss", "WishlistBoardsFragment发现wishList要修改")
                            wishList.apolloValue("collectStatus", it.latestCollectStatus)
                            viewBinding.rv.bindingAdapter.notifyItemChanged(index)
                            break
                        }
                    }
                }
            }
        }
    }
}